/*
	SlideScript - minimalistic top-down scripting language.
	(C) Copyright 2014-2022 Chris Dorman - some rights reserved (GPLv2)

	View README file supplied with this software for more details
*/

#define MY_GLOBAL

#define RES_UX3 1               /* resolve UX3 global variables */

#include "inc/deps.h"
#include "inc/eprintf.h"
#include "inc/util.h"
#include "inc/lexer.h"
#include "inc/pipe.h"
#include "inc/inset.h"
#include "inc/vars.h"

int main(int argc, char **argv) 
{
    int is_interactive = 0;
	FILE *script;
	char script_line[MAX_STRING_BUFSIZE+1];

    // set environment variables
    setenv("PATH", PATH, 0);

    if (argc == 1)
    {
        script = stdin;
        if (isatty (fileno (stdin))) is_interactive = 1;
    }
    else
    {
        parse_args (argc, argv);
        script = fopen (argv [1], "r");
	}
	
	/* check if config opens successfully */
	if(script == NULL) {
		printf("Error: failed to open %s.\n", argv[1]);
		exit(EXIT_FAILURE);
	}
		
	/* Run while loop if file isnt empty. */
	if (script != NULL) 
	{
        while (1)
        {
            char *return_dat;
            int pipechk;
            int varc, ii;

            if (is_interactive)
            {
                printf ("%s", ":ss:prompt: ");
                fflush (stdout);
            }

            /* parse each line from the script in order. */

		    if (fgets (script_line,
                sizeof(script_line), script) == NULL) break;

            ss_piping(script_line);

            pipechk = get_cmd_count();

    	    return_dat = process_line(spipe[0].command);

            // Blank line, getting up outta here.
            if(return_dat == NULL) continue;

            varc = get_var_count();
            if(pipechk > 1)
            {
                for(ii = 1; ii < pipechk; ii++)
                {
                    set_var(varc, "PIPE", return_dat);
                    // Process functions based on previous pipe return
                    return_dat = process_line(spipe[ii].command);

                    set_var(varc, "\0", "\0");

                    // Check to see if there's anything to even display
                    if(return_dat == NULL) 
                    {
                        continue;
                    }
                }
            }

            // Print the pipe line
            if(return_dat != NULL)
            {
                printf("%s\n", return_dat);
                fflush(stdout);
            }

            // Free used mallocs within QM_SS & QM_BQ
            qflush(QM_SS);
            qflush(QM_BQ);
		} /* end of while */
	} /* file null */

    /* Free variables after:
        a) scripts parsed or
        b) user session is over */
    qflush(QM_VARIABLES);
    if (argc != 1 ) fclose(script);
	exit(EXIT_SUCCESS);
}
